﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Mvc;
using TechEd.Data.Core.Entity;
using TechEd.Rest.Core.Interfaces;

namespace TechEd.Web.Controllers
{
	public class FileController : Controller
	{
		[HttpPost]
		public ActionResult Upload()
		{
			foreach (string inputTagName in Request.Files)
			{
				HttpPostedFileBase file = Request.Files[inputTagName];
				if (file != null && file.ContentLength > 0)
				{
					var contentType = file.ContentType;
					var fileName = file.FileName;

					var length = file.InputStream.Length;
					if (length > int.MaxValue)
						throw new ApplicationException("File length more than int.MaxValue");

					var bytes = new byte[length];

					file.InputStream.Read(bytes, 0, (int)length);

					using (ChannelFactory<IService1> factory = new ChannelFactory<IService1>(typeof(IService1).FullName))
					{
						VideoInfo videoInfo = factory.CreateChannel().UploadVideo(MvcApplication.ApplicationPrefix, fileName, bytes, contentType);
					}
				}
			}

			return RedirectToAction("Index", "Home");
		}

	}
}
